# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date: 
# @Last Modified by: CPS
# @Last Modified time: 2021-08-05 11:34:45.888952
# @file_path "Z:\CPS\IDE\SublimeText\sublime_text_4113.21_win64_test\Data\Packages\testt_fileheader"
# @Filename "file_header.py"
# @Description: 功能描述
#

import sublime
import sublime_plugin
import datetime
import os

TMPL_PATH = ""
PLUGIN_NAME = __package__
SETTING_FILE = "testt.sublime-settings"
SETTINGS = {}
FOLDER_LIST = {}
SETTINGS_KEY = "testt_fileheader"

from .core import utils

def get_floder_list() -> dict:
    return {
        'user_path':os.path.join(sublime.packages_path(),'User'),
        'default_settings':os.path.join(sublime.packages_path(), PLUGIN_NAME, '.sublime', SETTING_FILE),
        'user_settings':os.path.join(sublime.packages_path(),'User', SETTING_FILE),
        'tmplate_folder':os.path.join(sublime.packages_path(), PLUGIN_NAME, "headerTmpl")
    }

# 用户选择后的回调，将用户所选择的语法传给函数 testt_add_file_header
def get_user_select_syntax(index:float) -> None:
    if index != -1:
        sublime.active_window().run_command('testt_add_file_header', {"syntaxIndex": index})

def plugin_loaded():
    global FOLDER_LIST
    FOLDER_LIST = get_floder_list()

    def plugin_loaded_async():
        global SETTINGS
        with open(FOLDER_LIST['default_settings'], 'r', encoding='utf8') as f:
            SETTINGS = sublime.decode_value(f.read()).get(PLUGIN_NAME, {})
            if len(list(SETTINGS.keys())) == 0:
                raise Exception('读取配置失败 ~~~ 请确保一下文件真实存在： ', FOLDER_LIST['default_settings'])
            # print('读取settings 1: ', SETTINGS.keys())

        user_settings = sublime.load_settings(SETTING_FILE)
        utils.recursive_update(SETTINGS, user_settings.to_dict()[PLUGIN_NAME])
        user_settings.add_on_change(SETTING_FILE, _on_settings_change)

    def _on_settings_change() -> None:
        global SETTINGS

        tmp = sublime.load_settings(SETTING_FILE).get(PLUGIN_NAME, False)

        if not tmp or not isinstance(tmp, dict): return

        utils.recursive_update(SETTINGS, tmp)

        return

    # 在另一个进程执行该函数( 这样不会阻塞窗口的初始化，造成载入文件卡顿 )
    sublime.set_timeout_async(plugin_loaded_async)

class TesttAddFileHeaderCommand(sublime_plugin.TextCommand):
    def run(self, edit, syntaxIndex:int=-1):
        try:
            size = self.view.sel()[0].end()
            file_name = self.view.file_name()
            tmp_file = self.get_tmpl_file(file_name)

            # if isinstance(tmp_file, dict):
            if len(tmp_file) > 1:
                if syntaxIndex > -1:
                    tmp_file = tmp_file[list(tmp_file.keys())[int(syntaxIndex)]]
                    print('当前tmp_file: ', tmp_file)
                else:
                    sublime.active_window().show_quick_panel(tmp_file.keys(), get_user_select_syntax)
                    return
            else:
                tmp_file = tmp_file[list(tmp_file.keys())[0]]

            tmpl_info = self.get_header_info(file_name, size)
            header_info = self.replace_tmpl_info(tmp_file, tmpl_info)

            if header_info:
                self.insert_file_header(edit, header_info)

        except Exception as e:
            print('TesttAddFileHeaderCommand，发生错误: ')
            print(e)


    def insert_file_header(self, edit, header_info):
        cursor_offset = self.view.sel()[0].end()
        self.view.insert(edit,0,header_info) and self.view.show_at_center(cursor_offset)


    def set_tmpl_path(self, plugin_name):
        global TMPL_PATH
        TMPL_PATH = os.path.join(sublime.packages_path(), plugin_name, "headerTmpl")

    def get_tmpl_path(self):
        return TMPL_PATH

    def insertFileHeader(self,filename, size=0):
        # _settings = settings.get_settings()
        # _options = settings.get_options('file_header')
        # info = _options['headerInfo']
        info = SETTINGS['headerInfo']

        # 文件字符串少于2的话,当作是一个新文件,添加创建时间
        if size <= 1:
            info = self.on_add_file(filename, info)
        info = self.on_modi_file(filename, info)

    def get_header_info(self, filename, size=0):
        # _settings = settings.get_settings()
        # _options = settings.get_options('file_header')
        # info = _options['headerInfo']
        info = SETTINGS['headerInfo']

        # 文件字符串少于2的话,当作是一个新文件,添加创建时间
        if size <= 1:
            info = self.on_add_file(filename, info)
        info = self.on_modi_file(filename, info)
        return info

    def get_tmpl_file(self, filename:str) -> dict:
        # _settings = settings.get_options('file_header')
        # global SETTINGS

        _template = SETTINGS.get('template', {})

        # 检查当前后缀名是否存在对应的 tmpl 模板文件
        # ext = os.path.splitext(filename)[1].replace('.','')
        name, ext = os.path.basename(filename).split('.')
        res = {}
        if ext.lower() in _template.keys():
            if isinstance(_template[ext], list):
                # 当前格式存在多个模板 返回对象，给用户选择
                print('当前是列表中： ', _template[ext])
                for each in _template[ext]:
                    res[each] = os.path.join(FOLDER_LIST['tmplate_folder'], each)+'.tmpl'
            else:
                res[ext] = os.path.join(FOLDER_LIST['tmplate_folder'], _template[ext])+'.tmpl'

        return res

    def replace_tmpl_info(self, tmpl_file, info):
        if os.path.exists(tmpl_file):
            # 读取tmpl文件
            res = ''
            with open(tmpl_file,'r',encoding='utf8') as tmpl:
                for each in tmpl.readlines():
                    for key,val in info.items():
                        each = each.replace('{{'+key+'}}',val)
                    res+=each
            return res


    def on_add_file(self,filename,info):
        info['create_time'] = self.get_now(info['create_time'])
        return info

    def on_modi_file(self,filename, info):
        info['last_modified_time'] = self.get_now(info['last_modified_time'])
        info['file_path'] = os.path.dirname(filename)
        fn = os.path.basename(filename)

        if fn.startswith('index'):
          # 如果文件是 index.xxxx, 就把文件夹名作为文件名
          info['file_name'] = os.path.basename(info['file_path'])
        else:
          info['file_name'] = fn

        return info

    def get_now(self,fmat = r'%Y-%m-%d %H:%M:%S'):
        return datetime.datetime.now().__format__(fmat)

